package com.jt.util;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
//读写锁
public class RegistryTests {
    private static Map<String,String> registryMap= new HashMap<>();

//    public static void doRegist(String serviceId,String host){
//        registryMap.put(serviceId, host);
//    }
//    public static String doLookup(String serviceId){
//        return registryMap.get(serviceId);
//    }
    private static final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public  static void doRegist(String serviceId,String host){//悲观写

        readWriteLock.writeLock().lock();
        try {
            registryMap.put(serviceId, host);
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }
    //服务的发现,从map中基于key获取服务实例
    public  static String doLookup(String serviceId){//乐观读
        readWriteLock.readLock().lock();
        try {
            return registryMap.get(serviceId);
        }finally {
            readWriteLock.readLock().unlock();
        }
    }
    public static void main(String[] args) {
        String[] ip =new String[100];
        String[] hosts =new String[100];
        for (int i=0;i<ip.length;i++) {
            ip[i] = "ip" + i;
            hosts[i] = "hosts" + i;
        }
        Thread t1=new Thread(){
            @Override
            public void run() {
                for(int i=0;i<25;i++){
                    doRegist(ip[i],hosts[i]);
                }
            }
        };
        Thread t2=new Thread(){
            @Override
            public void run() {
                for(int i=25;i<50;i++){
                    doRegist(ip[i],hosts[i]);
                }
            }
        };
        Thread t3=new Thread(){
            @Override
            public void run() {
                for(int i=50;i<75;i++){
                    doRegist(ip[i],hosts[i]);
                }
            }
        };
        Thread t4=new Thread(){
            @Override
            public void run() {
                for(int i=75;i<100;i++){
                    doRegist(ip[i],hosts[i]);
                }
            }
        };
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
    }

